<?php

declare(strict_types=1);

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 *  每日任务记录
 */
class DailyTaskLog extends Model
{
    protected $table = 'daily_task_log';

    //未完成任务
    const STATUS_UNDO = 0;
    //已完成任务, 未领取
    const STATUS_DONE = 1;
    //已领取
    const STATUS_REWARD = 2;

    /**
     * The attributes that are mass assignable.
     * @var array
     */
    protected $fillable = [
        "user_id", "task_id", "flag"
    ];

    /**
     * 添加任务记录
     */
    static function addLog($userId = 0, $taskId = 0)
    {
        if (!$taskId || !$userId) return false;
        //今天是否有完成任务记录
        $todayTask = self::checkTodayTask($userId, $taskId);

        if ($todayTask) return false;
        $model = new self();
        $model->user_id = $userId;
        $model->task_id = $taskId;
        $model->flag = self::STATUS_DONE;
        $model->read = 0;
        Log::info(__CLASS__ . "==UserId:{$userId}==TaskId:=={$taskId}");
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 今天已完成任务
     */
    static function checkToday($userId = 0)
    {
        $where = [
            ['user_id', $userId],
            ['created_at', '>=', date('Y-m-d')],
        ];
        //设置已读
        self::where($where)->update(['read' => 1]);
        return self::where($where)->pluck('flag', 'task_id')->toArray();
    }

    /**
     * 今天已完成的某个任务记录
     */
    static function checkTodayTask($userId = 0, $taskId = 0)
    {
        $where = [
            ['user_id', $userId],
            ['created_at', '>=', date('Y-m-d')],
            ['task_id', $taskId]
        ];
        return self::where($where)->first();
    }

    /**
     * 获取不同角色不同类型的任务ID
     */
    static function getTaskId($type = '', $role = UserProfile::ROLE_HOST)
    {
        switch ($type) {
            case 'call':
                return $role == UserProfile::ROLE_HOST ? 3 : 102;
            case 'msg':
                return 1;
            case 'msg_frd':
                return 2;
            case 'moment':
                return $role == UserProfile::ROLE_HOST ? 4 : 103;
            case 'invite':
                return $role == UserProfile::ROLE_HOST ? 5 : 104;
            case 'recharge':
                return 101;
        }
    }
}
